/**
 @author Jacye.Ouyang
 */
/*Dependence: essential:GOLBAL_DATA; optional: gExchangeMap,gMICExangeMap */
/* control permission of accessing data from push server the exchanges */

var QS_PermissionChecker = function(permissionData,gExchMap,gMICMap){   // the permission data is from GOLBAL_DATA
    this.dataPermission = {1:{},10:{},20:{},8:{},3:{},7:{},9:{},11:{},16:{},13:{},2:{}};  
    this.modulePermission = {};
	this.exchangePermission ={};
    this.securityTypes = [1,10,3,20,2,8,7,9,11,16,13,3]; // 1:ST,ETF and CE; 10:index;
    this._ACBExchMap= {};
    this._init(permissionData,gExchMap,gMICMap);
};
QS_PermissionChecker.prototype = {
    _init:function(permissionData,gExchMap,gMICMap){
        var tExchMap = this._initDataPermission(permissionData.DataPermission);  
		this.exchangePermission= tExchMap;
        this._initACBExchMap(gExchMap,gMICMap,tExchMap);
    },
    _initDataPermission:function(data){
        var  tExchMap = {};
        if(data && data.length) {
            var idxs,secList = [],exch,type,code,idx;
            for(var i = 0; i < data.length;i++){
                secList = data[i]["sec"].replace(/,$/,"").split(","), exch = data[i]["exch"],
                type = data[i]["type"],code = data[i]["code"].replace(/,$/,"").split(","),ckidx = data[i]["ckIdx"];
                tExchMap[exch] = true;
                if(data[i]["sec"]== "-1"){ // index, stock,ETF and CE                // not index
                    if(!this.dataPermission[1][exch]){
                        this.dataPermission[1][exch] = {}
                    }
                    if(!this.dataPermission[10][exch]){
                        this.dataPermission[10][exch] = {}
                    }
                    if(!this.dataPermission[8][exch]){
                        this.dataPermission[8][exch] = {}
                    }
					if(!this.dataPermission[7][exch]){ // bond
                        this.dataPermission[7][exch] = {}
                    }
                    if(!this.dataPermission[9][exch]){// bond
                        this.dataPermission[9][exch] = {}
                    }
                    if(!this.dataPermission[11][exch]){// bond
                        this.dataPermission[11][exch] = {}
                    }
					if(!this.dataPermission[16][exch]){// bond
                        this.dataPermission[16][exch] = {}
                    }
					if(!this.dataPermission[13][exch]){// bond
                        this.dataPermission[13][exch] = {}
                    }//Spread
					if(!this.dataPermission[3][exch]){// bond
                        this.dataPermission[3][exch] = {}
                    }//Future
					if(!this.dataPermission[2][exch]){// bond
                        this.dataPermission[2][exch] = {}
                    }//Options*/
                    this.dataPermission[1][exch][type] = {code:code};
                    this.dataPermission[10][exch][type] = {code:code};
                    this.dataPermission[8][exch][type] = {code:code};
					this.dataPermission[7][exch][type] = {code:code};
                    this.dataPermission[9][exch][type] = {code:code};
                    this.dataPermission[11][exch][type] = {code:code};
					this.dataPermission[16][exch][type] = {code:code};
					this.dataPermission[13][exch][type] = {code:code};
					this.dataPermission[2][exch][type] = {code:code};
					this.dataPermission[3][exch][type] = {code:code};
                } else {   // other security type.
                    for(var j=0;j<secList.length;j++){
                        if(typeof(secList[j])=="undefined"||secList[j]=="") continue;
                        if(!this.dataPermission[secList[j]])this.dataPermission[secList[j]]= {};
                        if(!this.dataPermission[secList[j]][exch])this.dataPermission[secList[j]][exch]= {};
                        this.dataPermission[secList[j]][exch][type] = {code:code};
                        if(ckidx == 1){ // check the ticker in one exch.
                            this.dataPermission[secList[j]][exch][type] = {code:code,idx:data[i]["idx"].replace(/,$/,"").split(",")};
                        }     
                    }
                }
            }
            this.dataPermission[20]["245"] = {};
            this.dataPermission[20]["245"]["D"]={code:[-1]};  // add forex exchanges in permission.
            this.dataPermission[20]["240"] = {};
            this.dataPermission[20]["240"]["D"]={code:[-1]};  
            this.dataPermission[3]["64"] = {"D":{code:[-1]}};// add furture exchanges in permission.
            this.dataPermission[3]["66"] = {"D":{code:[-1]}};
            this.dataPermission[3]["67"] = {"D":{code:[-1]}};
            this.dataPermission[3]["77"] = {"D":{code:[-1]}}; 
            this.dataPermission[10]["27"] = {"D":{code:[-1]}}; // MSCI Indexs.
			this.dataPermission[10]["41"] = {"D":{code:[-1]}}; //indices.
        }
        return tExchMap;
    },
    getDataSource:function(exch,sectype,subcode){
        var sourcelist=this.dataPermission[sectype][exch];
        if(typeof subcode!="undefined"){
            for(var sourcetype in sourcelist){
                if($.inArray(subcode,sourcelist[sourcetype])!=-1){
                    return sourcetype;
                }
            }
        }else{
            return "R" in sourcelist?"R":"D";
        }
    },
    _initACBExchMap:function(gExchMap,gMICMap,tExchMap){
        if (typeof(gExchMap) == "undefined" || typeof(gMICMap) == "undefined") { //not map,it means there is has all permission for ACB
			this._ACBExchMap = null;
		} else {
			//            var tMICMap = {};
			//            for(var i in gMICMap){
			//                tMICMap[gMICMap[i]]= i;
			//            }
			//            for(var o in tExchMap){
			//                if(typeof(gExchMap[o])!= "undefined"&&typeof(tMICMap[gExchMap[o]])!="undefined") {  // has permission 
			//                    this._ACBExchMap[tMICMap[gExchMap[o]]] = true;
			//                }
			//            }
			var havePermissionExch = {};
			for (var ii in tExchMap) {
				if (typeof(gExchMap[ii]) != "undefined") {
					havePermissionExch[gExchMap[ii]] = true;
				}
			}
			for (var o in gMICMap) {
				if (typeof(gMICMap[o]) != "undefined" &&typeof(havePermissionExch[gMICMap[o]]) != "undefined"&&havePermissionExch[gMICMap[o]]===true) { // has permission 
					this._ACBExchMap[o] = true;
				}
			}
			
			this._ACBExchMap['FLIT'] = true;//hard code for forex
		}
    },
    /* provide interface to get the subcodes to subscribe data from Push or Pull server*/
    /* sType: tenfore security type. tExchange: tenfore exchange code, tTicker: tenfore Ticker,dataType:"D" or "R".*/
    getSubcodes:function(sType,tExchange,tTicker,dataType){  
        var subcode = [];
        if(this.dataPermission[sType]&&this.dataPermission[sType][tExchange]&&this.dataPermission[sType][tExchange][dataType]){
            if(sType==10&&this.dataPermission[sType][tExchange][dataType]["idx"]){// index need check the ticker is in the idx list
                if($.inArray(tTicker,this.dataPermission[sType][tExchange][dataType]["idx"])>-1){
                    subcode = this.dataPermission[sType][tExchange][dataType]["code"];
                }
            }else{
                subcode = this.dataPermission[sType][tExchange][dataType]["code"];
            }   
        }
        return subcode;
    },
    /* provide interface for auto-complete component to check permission */
    /*check the permission using MIC Code such as: XTSE,XNYS,XNAS. For USA security, you can use country id.*/
    checkACBPermission:function(micCode,countryId,exchId){
		if(typeof(exchId)!="undefined"&&this.exchangePermission[exchId]===true){
			return true;
		}  
        if(this._ACBExchMap == null)return true;
        return this._ACBExchMap[micCode]==true||(countryId=="USA"&&(this._ACBExchMap["NA"]== true||this._ACBExchMap["USCO"]== true));
    }  
};

var QS_Permission = new QS_PermissionChecker(GOLBAL_DATA,gExchangeMap,gMICExangeMap);  // 
delete GOLBAL_DATA.DataPermission;  // delete it from GOLBAL_DATA object.
   